import {Component, OnInit} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {StatusEnum} from '../../../core/enum/status.enum';
import {FilterEnum, FilterTypeEnum} from '../../../core/enum/filter.enum';
import {NzMessageService} from 'ng-zorro-antd';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {OtherUtil} from '../../../utils/other.util';
import { QuestionbankService } from './questionbank.service';

declare var $: any;

@Component({
  selector: 'app-questionbank-manage',
  templateUrl: './questionbank-manage.component.html',
  styleUrls: ['./questionbank-manage.component.scss'],
  providers: [QuestionbankService]
})
/**********题库管理*************/
export class QuestionbankManageComponent implements OnInit {
  // 主页面
  isLoading = false;
  // 树形结构操作
  pageInfo: PageEntity = new PageEntity();
  allList = [];
  displayList: Array<any> = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  isAllCheck = false;
  isIndeterminate = false;

  mainExciseType = null; // 主页面题型
  exciseContent = null; // 主页面试题内容
  mainStatus = 1; // 1.显示主页面，2.显示新增页面

  // 题分类
  exciseType = 1; // 试题类型默认单选，2：简答
  canDelete = true;
  typeId = null;
  param: QuestionParam = new QuestionParam();
  // 单选题
  singleText: any;

  // 单选题选项
  optItemList = [
    {
      name: '优',
      scoreRatio: 100,
      canEmpty: false
    },
    {
      name: '良',
      scoreRatio: 85,
      canEmpty: false
    },
    {
      name: '中',
      scoreRatio: 75,
      canEmpty: false
    },
    {
      name: '差',
      scoreRatio: 65,
      canEmpty: false
    }
  ];

  // 简答题
  shortText = null;
  moveTreeType = [];

  constructor(
    private service: QuestionbankService,
    private message: NzMessageService,
  ) {
  }

  ngOnInit() {
  }

  /***主界面树操作**/
  clickTree(event) {
    this.typeId = event.id;
    this.exciseContent = null;
    this.mainExciseType = null;
    this.pageInfo = new PageEntity();
    this.pageInfo.first = 1;
    this.pageInfo.totalRecords = 1;
    this.page();
  }

  /*****分页查询*********/
  page(): void {
    this.pageInfo.filters['classifyId'.toString()] = {
      matchMode: FilterEnum.EQUALS,
      value: this.typeId,
      whereType: FilterTypeEnum.AND
    };
    this.pageInfo.multiSortMeta = [
      {
        field: 'gmtCreate',
        order: -1
      }
    ];
    this.service.page(this.pageInfo).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
      }
    });
  }

  /*******第几页*******/
  searchPageIndex(event: any) {
    this.pageInfo.first = event;
    this.page();
  }

  /*******每页几条*****/
  searchPageSize(event: any) {
    this.pageInfo.rows = event;
    this.pageInfo.first = 1;
    this.page();
  }

  currentPageDataChange($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }

  /*******状态改变******/
  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  /**
   * 全选
   * @param value： value
   */
  checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  /**
   * 主页根据id删除逻辑
   */
  delByIdsLogic() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    return arr;
  }

  /******删除所选********/
  deleteAll() {
    const arr = this.delByIdsLogic();
    if (arr.length < 1) {
      this.message.warning('请勾选要删除的数据！');
      return;
    }
    this.service.deleteAll(arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.message.success(res.message);
        this.page();
      }
    });
  }


  /**
   * 点击删除一个
   * @param ids： id
   */
  deleteOne(ids: string) {
    this.service.delete(ids).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.message.success(res.message);
        this.page();
      }
    });
  }

  /********判断是否选择了数据需要删除**********/
  checkDelete(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  /*******点击查询*********/
  clickSearch() {
    this.pageInfo.first = 1;
    let ctext = null;
    if (this.exciseContent) {
      if (this.exciseContent.toString() === '+' || this.exciseContent.toString() === '*' || this.exciseContent.toString() === '\\') {
        ctext = '\\' + this.exciseContent;
      } else {
        ctext = this.exciseContent;
      }
    }
    this.exciseContent ? this.pageInfo.filters['content'.toString()] = {
      matchMode: FilterEnum.CONTAINS,
      value: ctext,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfo.filters['content'.toString()];
    this.mainExciseType ? this.pageInfo.filters['type'.toString()] = {
      matchMode: FilterEnum.EQUALS,
      value: this.mainExciseType,
      whereType: FilterTypeEnum.AND
    } : delete this.pageInfo.filters['type'.toString()];
    this.page();
  }

  /********点击重置**************/
  resetSearch() {
    this.exciseContent = null;
    this.mainExciseType = null;
    this.pageInfo.first = 1;
    delete this.pageInfo.filters['content'.toString()];
    delete this.pageInfo.filters['type'.toString()];
    this.page();
  }

  moveCloseFn(): void {
    this.mapOfCheckedId = {};
    this.canDelete = true;
    this.isAllCheck = false;
  }

  /******** 点击取消按钮********/
  cancelBack() {
    this.mainStatus = 1;
  }

  /******点击新增业务逻辑处理部分,初始化数据显示部分*********/
  clickAdd() {
    this.mainStatus = 2;
    this.findTreeList();
    this.param = new QuestionParam();
    this.param.type = '单选题'; // 默认单选题
    this.exciseType = 1;
    this.singleText = null;
    this.shortText = null;
    // 初始化单选数据
    this.clearSingle();
  }

  /*********清空单选题**********/
  clearSingle() {
    this.optItemList = [
      {
        name: '优',
        scoreRatio: 100,
        canEmpty: false
      },
      {
        name: '良',
        scoreRatio: 85,
        canEmpty: false
      },
      {
        name: '中',
        scoreRatio: 75,
        canEmpty: false
      },
      {
        name: '差',
        scoreRatio: 65,
        canEmpty: false
      }
    ];
  }

  /******分类题树列表**********/
  findTreeList() {
    this.service.fyfindAll({
      cols: ['id', 'name']
    }).subscribe(data => {
      if (data.status === StatusEnum.SUCCESS) {
        this.moveTreeType = data.datas;
      }
    });
  }


  /**
   * 点击编辑
   */
  edit(data) {
    this.findTreeList();
    this.param = new QuestionParam();
    this.mainStatus = 2;
    if (data.type === '单选题') {
      this.exciseType = 1;
      this.singleText = data.content;
      this.optItemList = data.selectList;
      if (this.optItemList && this.optItemList.length > 0) {
        this.optItemList.forEach(item => {
          item.canEmpty = Boolean(item.canEmpty);
        });
      }
      this.param.selectList = this.optItemList;
    } else if (data.type === '简答题') {
      this.exciseType = 2;
      this.shortText = data.content;
    }
    this.param.type = data.type;
    this.param.classifyId = data.classifyId;
    this.param.id = data.id;
    this.param.content = data.content;
  }


  /**
   * 试题列表改变时事件触发
   * @param event: e
   */
  typeChange(e) {
    this.param.content = null;
    if (e === '单选题') {
      this.exciseType = 1;
      this.shortText = null;
    } else if (e === '简答题') {
      this.exciseType = 2;
      this.param.selectList = [];
      this.singleText = null;
      // 初始化单选数据
      this.clearSingle();
    }
  }

  /**
   * 题新增新增保存/编辑保存
   * @param id i
   */
  submitExcise(): void {
    if (!this.param.type) {
      this.message.warning('请选择题型!');
      return;
    }
    if (!this.param.classifyId) {
      this.message.warning('请选择问题分类!');
      return;
    }

    // 处理单选题
    if (this.param.type === '单选题') {
      if (!this.singleText) {
        this.message.warning('请输入题目!');
        return;
      }
      this.param.content = this.singleText;
      let singleKey = false;
      for (const item of this.optItemList) {
        if (!item.name) {
          singleKey = true;
          break;
        }
        if (item.scoreRatio !== 0 && item.scoreRatio) {
        } else {
          singleKey = true;
          break;
        }
      }
      if (singleKey) {
        this.message.warning('选项或选项分值比例不能为空!');
        return;
      }
      this.param.selectList = this.optItemList;
      this.param.selectList.forEach(sel => {
        sel.canEmpty = Number(sel.canEmpty);
      });
    } else if (this.param.type === '简答题') {
      if (!this.shortText) {
        this.message.warning('请输入题目!');
        return;
      }
      this.param.content = this.shortText;
    }
    // 编辑提交
    const opt = this.param.id ? 'update' : 'create';
    this.service[opt](this.param).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.mainStatus = 1;
        this.page();
      }
    });
  }


  // 新增题目
  addTr(i) {
    this.optItemList.splice(i + 1, 0, {
      name: '',
      scoreRatio: null,
      canEmpty: false
    });
  }

  delTr(i) {
    if (this.optItemList.length === 1) {
      this.message.warning('第一项不能删除!');
      return;
    }
    this.optItemList.splice(i, 1);
  }

  /**
   * 排序
   */
  upDataItemType(ic: number) {
    if (ic !== 0) {
      this.optItemList = this.swapItems(this.optItemList, ic, ic - 1);
    } else {
      this.message.warning('已经到顶了!');
    }
  }

  /**
   * 排序
   */
  downDataItemType(ic: number) {
    if (ic !== this.optItemList.length - 1) {
      this.optItemList = this.swapItems(this.optItemList, ic, ic + 1);
    } else {
      this.message.warning('已经到底了!');
    }
  }

  /**
   * 排序
   */
  swapItems(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  }

  // 新增编辑返回
  back() {
    this.mainStatus = 1;
  }
}



/**
 * 试题参数
 */
class QuestionParam {
  id?: string;
  type?: string; // 类型:单选题、简答题
  classifyId?: string; // 分类id
  content?: string; // 题目内容
  // 选择题答案列表
  selectList?: Array<QuestionOptionParam> = [];
}

/**
 * 试题中的列表参数
 */
class QuestionOptionParam {
  id?: string;
  canEmpty?: any; // 允许填空
  name?: string;
  scoreRatio?: number; // 分值比例0-100（百分比）
}

